import React, { useCallback, useState } from 'react'
import { PullToRefresh } from 'antd-mobile';
// @ts-ignore
import Styles from './index.scss'


interface PropsInterface<T> {
  // height
  height: string | number
  // 渲染 item
  renderItem: (item: T) => JSX.Element
  // 数据数组
  dataArr: T[]
  // 异步加载数据
  asyncLoad: (pageNum: number, pageSize: number) => any
  // pageSize
  pageSize: number,
  // 初始化分页数
  pageNum: number
}

function Refresh<T>(props: PropsInterface<T>) {
  // 是否加载中
  const [isLoading, setLoading] = useState(false)
  // 分页
  const [pageNum, setPageNum] = useState(props.pageNum)
  // 是否加载全部
  const [finish, setFinish] = useState(false)

  const loadData = useCallback(async () => {
    if (isLoading) return
    setLoading(true)
    const list = await props.asyncLoad(pageNum, props.pageSize)
    setPageNum((num) => num + 1)
    setLoading(false)
    if (list.length < props.pageSize) {
      setFinish(true)
    }
  }, [isLoading, pageNum])

  if (finish) {
    return <>
      {props.dataArr.map(item => props.renderItem(item))}
      <p className={`w-text-center ${Styles.finish}`}>已经加载全部</p>
    </>
  }

  const RefreshDom = () => {
    // @ts-ignore
    return <PullToRefresh
      style={{
        height: props.height,
        overflow: 'auto',
      }}
      indicator={{
        activate: '上拉加载更多', deactivate: '加载完', release: '玩命加载中', finish: '加载完成'
      }}
      direction="up"
      refreshing={isLoading}
      onRefresh={() => {
        loadData()
      }}
    >
      {props.dataArr.map(item => props.renderItem(item))}
    </PullToRefresh>
  }

  return RefreshDom()
}

Refresh.defaultProps = {
  height: 'calc(100vh - 45px)',
  pageSize: 10,
  pageNum: 2
};

export default Refresh